package com.dudu.service.impl;

import java.io.IOException;
import java.util.Calendar;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;

import com.dudu.dao.SmsCodeDao;
import com.dudu.dao.SmsLogDao;
import com.dudu.model.SmsCode;
import com.dudu.model.SmsLog;
import com.dudu.service.ISmsCodeService;

import core.CoreDao;
import core.CoreDaoInvoke;
import core.CoreService;
/**
 * 短信+短信验证service
 * @author gaoxs
 *
 */
public class SmsCodeServiceImpl implements ISmsCodeService {

	private CoreDao coreDao = CoreDaoInvoke.getInstance();
	private SmsLogDao smsLogDao = new SmsLogDao();
	private SmsCodeDao smsCodeDao=new SmsCodeDao();
	/**
	 * 验证短信码是否正确
	 * @param phoneNum
	 * @param code
	 * @return
	 */
	public  boolean checkCode(String phoneNum, String code){
		boolean isTrue = false;
		SmsCode smsCode= smsCodeDao.query(coreDao, phoneNum);
		if(smsCode != null){
			String resultCode = smsCode.getCode();
			String deadLine = smsCode.getDead_line();
			long currentTime = Calendar.getInstance().getTimeInMillis();
			if(StringUtils.isNotBlank(deadLine) && currentTime < Float.valueOf(deadLine)){  //有效期内，有效期10分钟
				if(StringUtils.isNotBlank(resultCode) && resultCode.equals(code)){
					isTrue = true;
					smsCodeDao.delete(coreDao, phoneNum);
				}
			}
		}
		
		return isTrue;
	}
	
	/**
	 * 发验证码
	 * @param phoneNum
	 * @return
	 */
	public  String sendCode(String phoneNum){
		String reslut = "";
		String code = String.valueOf(RandomUtils.nextInt(10)) 
				    + String.valueOf(RandomUtils.nextInt(10))
				    + String.valueOf(RandomUtils.nextInt(10))
				    + String.valueOf(RandomUtils.nextInt(10))
				    + String.valueOf(RandomUtils.nextInt(10))
				    + String.valueOf(RandomUtils.nextInt(10));
		try {
			reslut = sendSms(phoneNum, "您要申请业务的短信验证码是："+code+"，验证码十分钟有效，如非本人操作请忽略本条短信。");
			CoreService.log.info("您要申请业务的短信验证码是："+code);
			if("0#1".equals(reslut)){
				reslut = "0";
			}
			//先删除未及时清理的验证码
			smsCodeDao.delete(coreDao, phoneNum);
			
			SmsCode smsCode = new SmsCode();
			smsCode.setCode(code);
			smsCode.setPhone(phoneNum);

	        Calendar cal = Calendar.getInstance();
	        cal.add(Calendar.MINUTE, 10);      //十分钟有效期
	        String dead_line = String.valueOf(cal.getTimeInMillis());
			smsCode.setDead_line(dead_line);
			
			smsCodeDao.insert(coreDao, smsCode);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return reslut;
	}
	/**
	 * 发短信
	 * @param phoneNbr
	 * @param smsContent
	 * @return
	 */
	public String sendSms(String phoneNbr, String smsContent) throws Throwable,
			IOException {
		String result = null;
		if (StringUtils.isNotBlank(phoneNbr)
				&& StringUtils.isNotBlank(smsContent)) {
			HttpClient client = new HttpClient();
			PostMethod post = new PostMethod("http://service2.hbsmservice.com:8080/sms_send2.do");
			post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
			NameValuePair[] data = { new NameValuePair("corp_id", "2eab001"),
					new NameValuePair("corp_pwd", "yyyd07"),
					new NameValuePair("corp_service", "10690148lt"),
					new NameValuePair("mobile", phoneNbr),
					new NameValuePair("msg_content", smsContent),
					new NameValuePair("corp_msg_id ", "18911850097"),
					new NameValuePair("ext ", "") };

			post.setRequestBody(data);
			client.executeMethod(post);
			Header[] headers = post.getResponseHeaders();
			int statusCode = post.getStatusCode();

			result = new String(post.getResponseBodyAsString().getBytes("gbk"));
			post.releaseConnection();
		}

		log(phoneNbr, smsContent, result);
		
		return result;
	}
	/**
	 * 短信日志
	 * @param phoneNum
	 * @param smsContent
	 * @param result
	 */
	private  void log(String phoneNum, String smsContent, String result){
		try{
			
			SmsLog smsLog = new SmsLog();
			smsLog.setIsv_name("能力平台接口");
			smsLog.setPhoneNbr(phoneNum);
			smsLog.setSms_content(smsContent);
			smsLog.setSend_result(result);
			
			smsLogDao.insert(coreDao, smsLog);
		}catch(Exception ex){
			//
		}
	}

}
